/**
 * title:学子商城采用promise封装mysql，多次使用
 * author :王占胜
 */

const mysql = require('mysql')
let opt = {
    host: '127.0.0.1',
    port: 3306,
    password: "",
    user: 'root',
    database: 'xz'
}
var connect = mysql.createConnection(opt)
connect.connect(err => {
    if (err) throw err
    console.log("数据库连接成功");
})

// 封装查询
// let sql = "select * from xz_user where uname = ?"
function chaxun(sql, uname) {
    return new Promise((resolve, reject) => {
        connect.query(sql, [uname], (err, datas) => {
            if (err) {
                reject(err)
            } else {
                resolve(datas)
            }
        })
    })
}
// 封装插入数据库
// let sql = "select * from xz_user"
function sqlname(sql, myid) {
    return new Promise((resolve, reject) => {
        connect.query(sql, [myid], (err, datas) => {
            if (err) {
                reject(err)
            } else {
                resolve(datas);
            }
        })
    })
}

// 封装更新上传
function updatesFn(sql3, ids1, ids2) {
    return new Promise((resolve, reject) => {
        let sql3 = "update xz_user set ? where uid = ?"
        connect.query(sql3, [ids1, ids2], (err, datas) => {
            if (err) {
                reject(err);
            } else {
                resolve(datas)
            }
        })
    })
}

//封装分页查询
function page(sql, start, size) {
    return new Promise((resolve, reject) => {
        connect.query(sql, [start, size], (err, datas) => {
            if (err) {
                reject(err)
            } else {
                resolve(datas)
            }
        })
    })
}

// 轮播查询
function searchLB(sql) {
    return new Promise((resolve, reject) => {
        connect.query(sql, (err, datas) => {
            if (err) {
                reject(err)
            } else {
                resolve(datas)
            }
        })
    })
}

//数据详情页连表查询 
function unite(sql,ids) {
    return new Promise((resolve, reject) => {
        connect.query(sql,[ids], (err, datas) => {
            if (err) {
                reject(err);
            }
            resolve(datas);
        })
    })
}

// let sql = "select * from  xz_laptop_pic inner join comput where id = laptop_id;"


module.exports = {
    sqlname,    //插入数据库
    chaxun,    //登录注册前查询
    updatesFn, //更新上传
    page,        //分页查询,
    searchLB,    //轮播查询
    unite         //连表查询
}
